# 示例：使用 geopandas 生成简单 GeoJSON (新版本兼容)
# 结合知乎文章方法：https://zhuanlan.zhihu.com/p/379985536
import geopandas as gpd
import requests
import json
import time
from urllib.parse import urljoin

def get_china_geojson_from_echarts():
    """从 ECharts 官方仓库获取中国地图数据"""
    urls = [
        "https://cdn.jsdelivr.net/npm/echarts@latest/map/json/china.json",
    ]
    
    for i, url in enumerate(urls):
        try:
            print(f"尝试数据源 {i+1}: {url}")
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()
            
            china_geojson = response.json()
            
            # 验证数据格式
            if china_geojson.get('type') == 'FeatureCollection' and 'features' in china_geojson:
                with open("china.json", "w", encoding="utf-8") as f:
                    json.dump(china_geojson, f, ensure_ascii=False, indent=2)
                
                print(f"成功从 {url} 获取中国地图数据")
                print(f"包含 {len(china_geojson['features'])} 个省份/地区")
                
                # 使用 geopandas 读取并验证
                china_gdf = gpd.read_file("china.json")
                return china_gdf
            else:
                print(f"数据格式不正确: {url}")
                
        except Exception as e:
            print(f"数据源 {i+1} 失败: {e}")
            continue
    
    return None

def get_china_geojson_from_natural_earth():
    """从 Natural Earth 获取中国地图数据"""
    try:
        print("尝试从 Natural Earth 获取数据...")
        # 使用 Natural Earth 的简化国家边界数据
        url = "https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_admin_0_countries.zip"
        
        world = gpd.read_file(url)
        china = world[world.ADMIN == 'China']
        
        if len(china) > 0:
            china.to_file("china_natural_earth.json", driver='GeoJSON')
            print("成功从 Natural Earth 获取中国地图数据")
            return china
        else:
            print("Natural Earth 数据中未找到中国")
            return None
            
    except Exception as e:
        print(f"Natural Earth 数据源失败: {e}")
        return None

def create_detailed_china_geojson():
    """创建一个更详细的中国地图 GeoJSON 示例（基于知乎文章方法）"""
    # 简化的中国主要省份边界坐标（经纬度）
    provinces = {
        "北京": [[116.4, 39.9]],
        "天津": [[117.2, 39.1]],
        "河北": [[114.5, 38.0]],
        "山西": [[112.5, 37.9]],
        "内蒙古": [[111.7, 40.8]],
        "辽宁": [[123.4, 41.8]],
        "吉林": [[125.3, 43.8]],
        "黑龙江": [[126.5, 45.7]],
        "上海": [[121.5, 31.2]],
        "江苏": [[118.8, 32.0]],
        "浙江": [[120.2, 30.3]],
        "安徽": [[117.3, 31.9]],
        "福建": [[119.3, 26.1]],
        "江西": [[115.9, 28.7]],
        "山东": [[117.0, 36.7]],
        "河南": [[113.7, 34.7]],
        "湖北": [[114.3, 30.6]],
        "湖南": [[113.0, 28.2]],
        "广东": [[113.3, 23.1]],
        "广西": [[108.3, 22.8]],
        "海南": [[110.3, 20.0]],
        "重庆": [[106.5, 29.6]],
        "四川": [[104.1, 30.7]],
        "贵州": [[106.7, 26.6]],
        "云南": [[102.7, 25.1]],
        "西藏": [[91.1, 29.9]],
        "陕西": [[108.9, 34.3]],
        "甘肃": [[103.8, 36.0]],
        "青海": [[101.8, 36.6]],
        "宁夏": [[106.3, 38.5]],
        "新疆": [[87.6, 43.8]]
    }
    
    features = []
    for province, coords in provinces.items():
        # 为每个省份创建一个简化的多边形（以省会为中心的小矩形）
        center_lon, center_lat = coords[0]
        # 创建一个小矩形作为省份的简化表示
        polygon_coords = [
            [center_lon - 0.5, center_lat - 0.3],
            [center_lon + 0.5, center_lat - 0.3],
            [center_lon + 0.5, center_lat + 0.3],
            [center_lon - 0.5, center_lat + 0.3],
            [center_lon - 0.5, center_lat - 0.3]
        ]
        
        feature = {
            "type": "Feature",
            "properties": {
                "name": province,
                "id": f"CN-{province}",
                "center": coords[0]
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [polygon_coords]
            }
        }
        features.append(feature)
    
    detailed_china = {
        "type": "FeatureCollection",
        "features": features
    }
    
    with open("china_detailed.json", "w", encoding="utf-8") as f:
        json.dump(detailed_china, f, ensure_ascii=False, indent=2)
    
    print(f"生成了包含 {len(features)} 个省份的详细中国地图示例: china_detailed.json")
    return detailed_china

def download_china_geojson_manual():
    """提供手动下载指南"""
    print("\n=== 手动下载中国地图数据指南 ===")
    print("如果自动下载失败，请手动下载以下文件之一：")
    print("1. ECharts 中国地图: https://github.com/apache/echarts/tree/master/map/json")
    print("2. Natural Earth 数据: https://www.naturalearthdata.com/downloads/")
    print("3. 阿里云数据可视化: https://datav.aliyun.com/portal/school/atlas/area_selector")
    print("\n下载后将文件重命名为 'china.json' 并放在当前目录")

# 执行主程序
if __name__ == "__main__":
    print("=== 中国地图 GeoJSON 数据获取工具 ===")
    print("基于知乎文章方法: https://zhuanlan.zhihu.com/p/379985536")
    print()
    
    # 方法1: 尝试从 ECharts 获取
    print("步骤1: 尝试从 ECharts 官方仓库获取...")
    china_data = get_china_geojson_from_echarts()
    
    # 方法2: 如果失败，尝试 Natural Earth
    if china_data is None:
        print("\n步骤2: 尝试从 Natural Earth 获取...")
        china_data = get_china_geojson_from_natural_earth()
    
    # 方法3: 如果都失败，创建详细示例
    if china_data is None:
        print("\n步骤3: 创建详细的中国地图示例...")
        create_detailed_china_geojson()
        download_china_geojson_manual()
    else:
        print(f"\n✅ 成功获取中国地图数据！")
        print(f"数据包含 {len(china_data)} 个地理要素")
        print("文件已保存为: china.json")
    
    print("\n=== 完成 ===")